<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload extends Vip_Controller {

    private $uid;
	function __construct ()
	{
		parent::__construct();
        $this->load->library('pagination');
		$this->load->library('form_validation');
        $this->uid = $this->session->userdata('user_id');
        $this->load->model('good_m');
        $this->load->model('category_m');
	}

    /**
     * 上传Excel并解析数据到数据库
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function upload_excel() {

        if(!$this->auth->is_login())
        {
            die('无权访问此页');
        }
        $path = 'uploads/excel/'.$this->uid."/";
        $path_url=FCPATH.$path;
        if(!file_exists($path_url)){
            mkdir($path_url,0777,true);
        }
        //原文件名
        $file_name = $_FILES['uploadFile']['name'];
        //获得文件扩展名
        $temp_arr = explode(".", $file_name);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);
        //服务器上临时文件名
        $tmp_name = $_FILES['uploadFile']['tmp_name'];
        //新文件名
        $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
        //移动文件
        $file_path = $path . $new_file_name;
        if (move_uploaded_file($tmp_name, $file_path) === false) {
            alert("上传文件失败。");
        }
        @chmod($file_path, 0644);
        $pathinfo = $path_url.$new_file_name;
//        $pathinfo =  FCPATH.'uploads/excel/50/20180530011115_47919.xlsx';
        $excel_data = importExecl($pathinfo);
        if(!empty($excel_data)){
            foreach ($excel_data as $key=>$val){
                if($key > 2){
                    $cate_name = $val['A'];
                    // 通过分类名反差分类id
                    $ate_info = $this->category_m->get_row_by_catename($cate_name);
                    $row['good_category'] = $ate_info['id'];
                    $row['good_title'] = $val['B'];
                    $row['good_memo'] = $val['C'];
                    $row['good_price'] = $val['D'];
                    $row['good_content'] = $val['E'];
                    $row['good_part_number'] = $val['F'];
                    $row['user_id'] = $this->uid;
                    $this->good_m->add_shop_goods($row);
                }

            }
        }
        $data['msg']  = '上传成功!';
        $data['status']  = 200;
        echo json_encode($data);exit();

    }
    /**
     * 生成模板
     */
    public function create_excel_template(){

        $this->load->model('category_m');
        $category = $this->category_m->get_all_cates();

        if(!empty($category)){
            $cateStr = "";
            foreach ($category as $key=>$value){
                $cateStr .= $value['category_name'].',';
            }
        }
        $cateStr = substr($cateStr,0,strlen($cateStr)-1);
//        pp($cateStr);exit();

        require_once(APPPATH.'third_party/PHPExcel.php');
        require_once(APPPATH.'third_party/PHPExcel/Writer/Excel2007.php');
        require_once(APPPATH.'third_party/PHPExcel/IOFactory.php');

        $headArr = array("分类(下拉)","货品名称(必填)","货品规格(必填)","单价(必填)","生产工艺(必填)","料号(选填)");
        //创建新的PHPExcel对象
        $objPHPExcel = new PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $key += 1;
        }
        $key2 = ord("A");
        $example = array("胶带","PO胶袋","230*320","3.6","小边开口","");
        foreach($example as $v){
            $colum2 = chr($key2);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum2.'2', $v);
            $key2 += 1;
        }

        $objActSheet = $objPHPExcel->getActiveSheet();

        for ($k = 3; $k<500; $k++){
            $objValidation = $objActSheet->getCell("A".$k)->getDataValidation(); //这一句为要设置数据有效性的单元格

            $objValidation -> setType(PHPExcel_Cell_DataValidation::TYPE_LIST)
                -> setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION)
                -> setAllowBlank(false)
                -> setShowInputMessage(true)
                -> setShowErrorMessage(true)
                -> setShowDropDown(true)
                -> setErrorTitle('输入的值有误')
                -> setError('您输入的值不在下拉框列表内.')
                -> setPromptTitle('产品分类')
                -> setFormula1('"'.$cateStr.'"');
        }

        $objActSheet->getColumnDimension('a')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('b')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('c')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('d')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('e')->setWidth(25);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('f')->setWidth(20);//改变此处设置的长度数值

        $fileName = "excel_template.xlsx";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        //将输出重定向到一个客户端web浏览器(Excel2007)
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $Path='upload/excel_template/';
        $savePath=FCPATH.$Path;
        if(!file_exists($savePath)){
            mkdir($savePath,0777,true);
        }
        $savename=$savePath.$fileName;

        $objWriter->save($savename); //脚本方式运行，保存在当前目录

        echo $savename;exit();
    }
}